import { Suspect } from '../../module/suspect.js'
const Api = new Suspect()

// ju_sign/suspect/content.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    reward_list: [], //奖品列表
    answer_list: [], // 答案选项数组
    question_true_id: '',
    activity_id: '',
    question_list: [],
    question_img: '', // 问题图片类型
    question_name: '', // 问题文本类型
    answer_true: '',
    answer_show_type: '', //答案展示样式
    currentTime: 10, //答题倒计时时限
    pageNum: 0, //总题数
    score: 0, //单题基础分数
    total_score: 0, //答对题得分
    is_point: 0, //是否开启提示
    is_share: 0, //能否分享
    point_num: 0, //提示次数
    footer_bar_color: '#fcf270',
    currentNum: 0, //当前进度条关数
    guanNum: 0, //当前关数
    answer_show_type: 1, //答案框展示样式
    isCanAnswer: true,
    isGet: false, //能否领奖
    share_title: "快来帮帮我",
    title: "", //页面标题
    progress: 25,
    animationSate: '',
    musicSrc: '',
    show: true,
    isNext: true,
    selectNum: null,
    ongift: '',
    pupopReward: false // 奖励弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    this.setData({
      activity_id: options.activity_id,
      musicSrc: options.music
    })

    this.Music = wx.getBackgroundAudioManager()
    // this._Music()

    this.Music.onEnded(() => { // 音乐自然结束事件
      this._Music()
    })

    this.Music.onPause(() => {
      this.setData({
        animationSate: 'animation-play-state: paused'
      })
    })

    this.Music.onPlay(() => {
      this.setData({
        animationSate: 'animation-play-state: running'
      })
    })
  },

  onTapMusicBtn() { // 点击音乐按钮事件
    this.Music.paused ? this.Music.play() : this.Music.pause()
    this._animationSate(this.Music.paused)
  },

  _animationSate(type) {
    this.setData({
      animationSate: 'animation-play-state:' + (type ? 'paused' : 'running')
    })
  },

  _Music() {
    if (this.data.musicSrc == '') {
      return 
    }

    this.Music.title = '猜灯谜'
    this.Music.src = this.data.musicSrc 

    this.Music.play()
  },
  //点击答案
  onSelected({
    currentTarget
  }) {
    clearInterval(this.interval);
    if (!this._isNextFn()) {
      wx.showToast({
        title: '您已答题完毕',
        icon: 'none'
      })
      return false
    }

    let index = currentTarget.dataset.index ? currentTarget.dataset.index : 0
    let currentNum = this.data.currentNum
    this._SelectNum(index)
    this._doAnswer(index)

  },

  startNextTopic(result, point) {
    let pageNum = this.data.pageNum
    // let currentNum = this.data.currentNum
    if (result == 'yes') { //答对题加分,答对题目数加一
      this.setData({
        // currentNum: currentNum + 1,
        total_score: this.data.total_score + this.data.score,
      })
    }

    let currentTime = this.data.currentTime // 获取答题时间
    Api.nextQuestion({
      activity_id: this.data.activity_id,
      question_true_id: this.data.question_true_id,
      result: result,
      point: point,
      use_times: currentTime
    }).then((data) => {
      this.setData({
        selectNum: null,
        activity_id: data.activity_id,
        question_name: data.question_name,
        answer_list: this._filerList(data),
        currentTime: data.answer_times,
        point_num: data.point_num,
        is_point: data.is_point,
        question_true_id: data.id,
        currentNum: data.answer,
        answer_true: data.answers
      });

      //清除上一次的定时器
      clearInterval(this.interval);

      if (pageNum == data.answer) { //如果题答对答完，奖品图标颤抖
        this.setData({
          ongift: 'gelatine',
          isGet: true,
          isCanAnswer: false
        })
      } else if (data.total_answer >= pageNum) {
        this.setData({
          currentTime : 0,
          isCanAnswer : false
        })
      }else{
        //加载本次题计时器
        this._interval();
      }
    })
    .catch((err) => {
      wx.showToast({ title: err, icon: 'none' })
    });
  },

  _SelectNum(index = null) {
    this.setData({
      selectNum: index
    })
  },

  _isNextFn() {
    let pageNum = this.data.pageNum
    let currentNum = this.data.currentNum
    if (pageNum == currentNum) {
      return false
    } else {
      return true
    }
  },

  _doAnswer: function(answer_index) {
    //看答题机会是否用完
    var isAddAnswer = this._isAddAnswer();
    var isCanAnswer = this.data.isCanAnswer;
    if (!isCanAnswer) {
      return;
    }
    var title, result, contents, point
    if ((answer_index + 1) == this.data.answer_true) {
      title = '恭喜你答对啦'
      result = 'yes'
      point = 'no'
      contents = `正确答案是：${this.data.answer_list[this.data.answer_true - 1]}`
    } else {
      title = '很遗憾，答错了'
      result = 'no'
      contents = `赶紧拿小本本记下吧`
      point = 'no'
    }

    wx.showModal({
      title: title,
      content: contents,
      showCancel: false,
      confirmText: '下一题',
      confirmColor: '#bc0000',
      success: (res) => {
        if (res.confirm) {
          this._SelectNum()
          this.startNextTopic(result, point)
        }
      }
    })
  },
  /**
   * 点击提示按钮操作
   */
  onTapPrompt({
    currentTarget
  }) {
    if ((this.data.currentNum >= this.data.pageNum) || (this.data.guanNum >= this.data.pageNum)) {
      wx.showToast({
        title: `您已答题完毕`,
        icon: 'none'
      })
      return;
    } else {
      this._isAddAnswer();
    }
    if(this.data.isCanAnswer == false){
      return;
    }
    var point_num = currentTarget.dataset.index ? currentTarget.dataset.index : 0
    if (parseInt(point_num) <= 0 || !point_num) {
      console.log(parseInt(point_num));
      wx.showToast({
        title: `提示次数已经用完，展现你真正的实力吧`,
        icon: 'none'
      })
      return;
    }
    clearInterval(this.interval);
    var result = 'yes'
    var point = 'yes'
    wx.showModal({
      title: '提示',
      content: `正确答案是：${this.data.answer_list[this.data.answer_true - 1]}`,
      showCancel: false,
      confirmText: '下一题',
      confirmColor: '#bc0000',
      success: (res) => {
        if (res.confirm) {
          this._SelectNum()
          this.startNextTopic(result, point)
        }
      }
    })
  },
  /**
   * 刚进入答题页获取数据
   */
  getContent: function() {
    var that = this
    Api.content(this.data.activity_id).then((data) => {
      that.setData({
        question_credit: data.suspect.data.question_credit,
        answer_bg: data.suspect.data.answer_bg,
        answer_list: that._filerList(data.suspect_content),
        answer_show_type: data.suspect.data.answer_show_type,
        question_name: data.suspect_content.question_name,
        question_img: data.suspect_content.question_img,
        answer_true: data.suspect_content.answers,
        pageNum: data.suspect.data.question_num,
        footer_bar_color: data.suspect.data.footer_bar_color,
        question_true_id: data.suspect_content.id,
        total_score: data.suspect_user.total_score,
        score: data.suspect.data.score,
        currentNum: data.suspect_user.answer,
        point_num: data.suspect_user.point_num,
        is_point: data.suspect.data.is_point,
        credits: data.credits,
        currentTime: data.suspect.data.answer_times,
        answer_times: data.suspect.data.answer_times,
        is_share: data.suspect.data.is_share,
        share_title: data.suspect.data.share_title,
        title: data.suspect.data.title
      });
      wx.setNavigationBarTitle({
        title: that.data.title
      });

      if (data.suspect_user.answer == data.suspect.data.question_num) {
        //如果已经答完题清除计时器
        clearInterval(this.interval);
        that.setData({
          isGet: true,
          ongift: 'gelatine',
          currentTime: 0,
        });  
      } else if(data.suspect_user.total_answer >= data.suspect.data.question_num) {
        that.setData({
          currentTime: 0,
        }); 
        clearInterval(this.interval);
      }else{
        that._interval();
      }
    })
    .catch((err) => {
      wx.showToast({ title: err, icon: 'none' })
    })
  },

  /**
   * 领取奖励
   *
   */
  getPrize: function() {
    // clearInterval(this.interval);
    var that = this;
    var isGet = that.data.isGet;
    var ongift = that.data.ongift;
    if (!isGet && ongift == 'ongift') {
      return false;
    } else {
      this._getPrizeTrue();
    }
  },
  /**
   * //将试题答案装入列表
   */
  _filerList: function(data) {
    let newList = []
    this.setData({
      answer_list: []
    });
    for (var i = 0; i < 6; i++) {
      if (data[`choice${i + 1}`] != '' && data[`choice${i + 1}`] != null) {
        newList.push(data[`choice${i + 1}`]);
      }
    };
    return newList
  },
  /**
   * 定时器
   */
  _interval: function() {
    var that = this
    this.interval = setInterval(function() {
      var new_currentTime = that.data.currentTime;
      new_currentTime--;
      that.setData({
        currentTime: new_currentTime,
      })
      console.log(new_currentTime);
      if (new_currentTime <= 0) {
        clearInterval(that.interval);
        if (that.data.currentNum < that.data.pageNum) {
          that._doAnswer();
        }
      }
    }, 1000);

  },

  _isAddAnswer: function() {
    var that = this
    Api.isCanAnswer(this.data.activity_id).then((data) => {
      if (data.status == 1) {
        wx.showModal({
          title: '提示',
          content: `很遗憾答题次数用完，您可以点击兑换按钮，消耗${this.data.question_credit}积分获得一道补答机会`,
          showCancel: true,
          confirmText: '兑换',
          confirmColor: '#bc0000',
          success: (res) => {
            if (res.confirm) {
              this._CreditGetQuestion()
              //this.startNextTopic(result, point)
            } else
            if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

        this.setData({
          isCanAnswer: false,
          selectNum: null
        });
        return false;
      } else {
        this.setData({
          isCanAnswer: true
        });
        return true;
      }
    })
    .catch((err) => {
      wx.showToast({ title: err, icon: 'none' })
    })
  },

  /**
   * 用积分兑换答题机会
   */
  _CreditGetQuestion: function() {
    Api.creditGetQuestion(this.data.activity_id)
      .then((data) => {
        if (data.status) {
          // var message = '恭喜你成功兑换一次答题机会，点击确定答题吧'
          this.setData({
            isCanAnswer: true,
            currentTime: this.data.answer_times,
            credits: data.user_info.credits
          });
          this._interval();
        } else {
          var message = '积分不足，无法兑换'
          wx.showModal({
            title: '提示',
            content: message,
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#bc0000',
            success: (res) => {
              if (res.confirm) {
                clearInterval(this.interval);
              }
            }
          })
          this.setData({
            isCanAnswer: false
          });
        }
      })
      .catch((err) => {
        wx.showToast({ title: err, icon: 'none' })
      })
  },
  /**
   * 领奖方法
   */
  _getPrizeTrue: function() {
    Api.getPrize(this.data.activity_id).then((data) => {
      if (data.status == 1) {
        var message = '领取成功'
      };
      if (data.status == 2) {
        var message = '奖励已发放，请前往个人中心查看'
      };
      wx.showModal({
        title: '提示',
        content: message,
        showCancel: false,
        confirmText: '奖品详情',
        confirmColor: '#bc0000',
        success: (res) => {
          if (res.confirm) {
            clearInterval(this.interval);
            // this.getContent();
            this.ajaxShowPrize() // 调用查看奖品的方法
          }
        }
      })
    }).catch((err) => {
      wx.showToast({ title: err, icon: 'none' })
    })
  },

  ajaxShowPrize() { // 请求查看奖品
    let activity_id = this.data.activity_id
    Api.showPrize(activity_id)
    .then((res) => {
      this.setData({
        reward_list: res,
        pupopReward: true
      })
    })
  },
  pupopRewardClose() {
    this.setData({
      pupopReward: false
    }) // 关闭弹窗
    wx.navigateBack()
  },

  onRewardReceive() { // 弹窗领取奖励方法
    this.setData({
      pupopReward: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getContent()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearInterval(this.interval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(this.interval);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(options) {
    var that = this;
    let title = that.data.share_title;
    let shareData = {
      title: title,
      path: `/ju_sign/suspect/index?id=${this.data.activity_id}`
    }
    this._shareGetPoint()
    return shareData
  },

  _shareGetPoint: function() {
    let that = this
    Api.shareGetPoint(this.data.activity_id)
      .then((data) => {
        if (data.status == 1) {
          that.setData({
            point_num: that.data.point_num + 1
          })
        }
      })
      .catch((err) => {
        app.toast(err);
        wx.showToast({ title: err, icon: 'none' })
      });
  }
})